import { GET_LIST_DATA, LEFT_CLICK, ADD_SELECT_ITEM, MINUS_SELECT_ITEM, SHOW_CHOOSE_CONTENT, CLEAR_CAR } from "../actions/actionTypes"
const initState = {
    listData: {},
    currentLeftIndex: 0,
    showChooseContent: false
}
const getListData = (state, action) => {
    return {
        ...state, listData: action.obj.data
    }
}
const itemClick = (state, action) => {
    return {
        ...state,
        currentLeftIndex: action.obj.currentLeftIndex
    }
}
const addSelectItem = (state, action) => {
    return dealWithSelectItem(ADD_SELECT_ITEM, state, action)
}

const dealWithSelectItem = (type, state, action) => {
    let { listData, currentLeftIndex } = state;


    let list = listData.food_spu_tags || [];

    let currentItem = list[action.outIndex || currentLeftIndex];

    if (type === ADD_SELECT_ITEM) {

        currentItem.spus[action.obj.index].chooseCount++
    } else {

        currentItem.spus[action.obj.index].chooseCount--
    }

    let _listData = JSON.parse(JSON.stringify(listData))

    return {
        ...state,
        listData: _listData
    }
}

const minusSelectItem = (state, action) => {
    return dealWithSelectItem(MINUS_SELECT_ITEM, state, action)
}

const showChoose = (state, action) => {
    let _showChooseContent = action.obj.flag || false
    return {
        ...state,
        showChooseContent: _showChooseContent
    }
}

const clearCar = (state) => {
    let listData = state.listData;

    let list = listData.food_spu_tags || [];

    for (let i = 0; i < list.length; i++) {
        let spus = list[i].spus || [];
        for (let j = 0; j < spus.length; j++) {
            spus[j].chooseCount = 0;
        }
    }
    return { ...state, listData: JSON.parse(JSON.stringify(listData)) }
}

const menuReducer = (state = initState, action) => {
    switch (action.type) {
        case GET_LIST_DATA:
            return getListData(state, action)
        case LEFT_CLICK:
            return itemClick(state, action)
        case ADD_SELECT_ITEM:
            return addSelectItem(state, action)
        case MINUS_SELECT_ITEM:
            return minusSelectItem(state, action)
        case SHOW_CHOOSE_CONTENT:
            return showChoose(state, action)
        case CLEAR_CAR:
            return clearCar(state, action)
        default: return state
    }
}
export default menuReducer